package com.rzico.sbl.ui.statistic

import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityUnionStationBinding
import com.rzico.sbl.model.UnionChart
import com.rzico.sbl.model.UnionStation
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.StatisticUnionViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseRootActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.htmlSmallColor
import com.xinnuo.slimadapter.SlimAdapter

class UnionStationActivity : BaseRootActivity() {

    private lateinit var mBinding: ActivityUnionStationBinding

    // 销量统计
    private val mTotalList = ArrayList<UnionChart>()
    private var mDateMode = "3"
    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()
    private var mTotalType = ""

    override fun getViewModel() = get<StatisticUnionViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityUnionStationBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        transparentStatusBar()

        initListener()
        initData()
        initLayout()
        initTabLayout()

        getReportData()
    }

    override fun initData() {
        mBinding.also {
            it.stationMoney.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTotalList.indices) ""
                    else
                        mTotalList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }
    }

    /**
     * 初始化布局
     */
    private fun initLayout() {
        mBinding.apply {
            emptyLayout
                .also {
                    it.emptyImg.gone()
                    it.emptyHint.text = "暂无相关水站信息！"
                }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<UnionStation>(R.layout.item_statistic_union_station) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_union_title, bean.name)
                            text(R.id.item_union_name, bean.linkman.orEmpty("无"))
                            text(R.id.item_union_phone, bean.phone.orEmpty())
                            text(R.id.item_union_adress, bean.address)
                            text(R.id.item_union_total, bean.amount.formatDecimal())
                            text(R.id.item_union_count, bean.quantity)
                            text(R.id.item_union_amount, bean.settleTotal.formatDecimal())

                            visibility(
                                R.id.item_union_total_ll,
                                visibleValue { mTotalType == "out" }
                            )

                            with<TextView>(R.id.item_union_adress) {
                                it.isGone = bean.address.isNullOrEmpty()
                                it.text = bean.address
                            }

                            with<ImageView>(R.id.item_union_img) {
                                it.loadCircleImage(bean.logo)
                            }

                            clicked {
                                startActivityEx<UnionOrderActivity>(
                                    "type" to mTotalType,
                                    "enterpriseId" to bean.enterpriseId,
                                    "enterpriseName" to bean.name,
                                    "dateMode" to mDateMode,
                                    "beginDate" to mBeginDate,
                                    "endDate" to mEndDate
                                )
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    /**
     * 监听方法
     */
    override fun initListener() {
        mBinding.apply {
            stationMoneyTime.addTimeListener { start, end, hint ->
                mDateMode = when (hint) {
                    "近7天" -> "3"
                    "本月" -> "4"
                    "上月" -> "5"
                    else -> "7"
                }

                mBeginDate = start
                mEndDate = end

                getViewModel().cancelRequest()
                getReportData()
                updateList()
            }
        }
    }

    /**
     * TabLayout 初始化
     */
    private fun initTabLayout() {
        mBinding
            .stationTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mTotalType = when (it.position) {
                                1 -> "in"
                                else -> "out"
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "转出订单"
                    },
                    true
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "接收订单"
                    },
                    false
                )
            }
    }

    /**
     * 设置收支统计数据
     */
    private fun setMoneyChart() {
        mBinding
            .stationTab
            .apply {
                getTabAt(0)?.let { tab ->
                    tab.customView
                        ?.find<TextView>(R.id.item_tab_title)
                        ?.apply {
                            val valueHint = "¥${
                                mTotalList.sumOf {
                                    it.outPrice.doubleValue
                                }.formatDecimal()
                            }"

                            text = htmlSmallColor("转出订单$valueHint", valueHint)
                        }
                }
                getTabAt(1)?.let { tab ->
                    tab.customView
                        ?.find<TextView>(R.id.item_tab_title)
                        ?.apply {
                            val valueHint = "¥${
                                mTotalList.sumOf {
                                    it.inPrice.doubleValue
                                }.formatDecimal()
                            }"

                            text = htmlSmallColor("接收订单$valueHint", valueHint)
                        }
                }
            }

        mBinding
            .stationMoney
            .apply {
                if (mTotalList.isEmpty()) clear()
                else {
                    setGroupData(
                        entries = arrayListOf(
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.outPrice.floatValue
                                )
                            },
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.inPrice.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().settleColor(),
                        labelList = listOf(
                            "转出订单(总商品:${mTotalList.sumOf { it.outQuantity.intValue }})",
                            "接收订单(总商品:${mTotalList.sumOf { it.inQuantity.intValue }})"
                        ),
                        xFromValue = 0f
                    )
                }

                animateY(500)
            }
    }

    /**
     * 获取柱状图图数据
     */
    private fun getReportData() {
        getViewModel()
            .reportSettle(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mTotalList.clear()
                    mTotalList.addItems(it)

                    setMoneyChart()
                }
            )
    }

    /**
     * 收支结算水站列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .settleStation(
                page = index,
                type = mTotalType,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding.apply {
                        swipeRefresh.isRefreshing = false

                        emptyLayout
                            .emptyView
                            .isVisible = mList.isEmpty()
                    }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding.apply {
            swipeRefresh.isRefreshing = true

            emptyLayout
                .emptyView
                .gone()
        }

        mList.notEmpty {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}